<?php
namespace app\pc\logic;
use think\Cache;
use think\Request;
use think\captcha\Captcha;
use app\pc\validate\Login as LoginValidate;
/**
 * Class descript.
 * User: chan
 * Date: 2017/10/26 15:30
 */
class Login extends \app\pc\BaseModel
{

    //检测参数是否已传
    protected $ParameterDetection  = [
        'login'=>['account','passwd','code'],
        'registered'=>['account','passwd','code']
    ];

    /**
     * 用户登陆
     * @return array
     */
    public function login()
    {
        $condition['account'] = $this->requestData['account'];
        $root = db('member')->where($condition)->find();
        if(!$root) return array('message'=>'账号不存在');

        $code = $this->requestData['code'];
        if(!$this->check_verify($code))return array('message'=>'验证码有误!');

        $passwd = $this->requestData['passwd'];
        if(md5($passwd) != $root['passwd']) return array('message'=>'密码不正确!');
        unset($root['passwd']);
        $Oauth2 =  new \app\pc\service\Oauth2();

        //返回生成token
        return $Oauth2::generateToken($root);
    }

    /**
    *   用户注册
    *
    */
    public function registered(){
        $condition['account'] = $this->requestData['account'];
        $root = db('member')->where($condition)->find();
        if(!empty($root)) return array('message'=>'该账号已注册过!');
        $code = $this->requestData['code'];
        if(!$this->check_verify($code))return array('message'=>'验证码有误!');


        $data['account'] = $this->requestData['account'];
        $data['passwd'] = md5($this->requestData['passwd']);

        $res = db('member')->insert($data);

        if(!$res)return ['message'=>'注册失败!'];
    }

    /**
    *   验证码
    */
    public function captchaImg()
    {   
        $config =    [
            'codeSet'     =>'1234567890',
        // 验证码字体大小
            'fontSize'    =>    30,
        // 验证码位数
            'length'      =>    4,
        // 关闭验证码杂点
            'useNoise'    =>    true,
        ];
        $captcha = new Captcha($config);
        $code = $captcha->set_code();
        $code_string = implode("", $code);
        $code_md5 = md5($code_string);
        Cache::set('registered',$code_md5,3600);
        return $code;
    }

    /**
     * 检测输入的验证码是否正确
     *
     * @param $code 为用户输入的验证码字符串，
     * @param $id 多个验证码标识
     *
     */
    function check_verify($code, $id = ''){
        $iscode = md5($code);
        $boolcode = Cache::get('registered');
        Cache::set('registered',null); 
        if($boolcode != $iscode){
            return false;
        }else{
            return true;
        }
    }
}